package com.bidevalution.controller.api;

import com.bidevalution.business.service.*;
import com.bidevalution.controller.dto.BeEvalutionExpertDTO;
import com.bidevalution.controller.util.RequestUtil;
import com.bidevalution.dao.entity.BeSectionExpertInfo;
import com.bidevalution.dao.entity.BeSectionExpertProgress;
import com.bidevalution.dao.entity.BeSectionStep;
import com.bidevalution.service.layout.ColumnHeader;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.exception.BizException;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.model.Response;
import com.qtp.core.util.GsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * @修改记录
 * 2020-04-07 whc ZTKP-3481 添加终止项目
 * 2020-05-12 夏云飞 需求 QZRJ-13700 下拉选择框需支持打勾打叉之外的状态（请选择的状态）
 */
/**
 * @author daizhifeng
 * @version V2.0
 * @Description: 专家评审明细
 * @date 2019年9月12日 下午4:43:19
 *
 */
@Log4j2
@RestController
@RequestMapping("/beEvalutionExpert")
@Api(tags = "专家评审明细")
public class BeEvalutionExpertController extends BaseController {

    @Autowired
    private BeEvalutionExpertService beEvalutionExpertService;
    @Autowired
    private BeSectionExpertInfoService beSectionExpertInfoService;
    @Autowired
    private BeSectionStepService beSectionStepService;
    @Autowired
    private BeSectionExpertProgressService beSectionExpertProgressService;

    @Autowired
    private BeEvalutionOutcomeService beEvalutionOutcomeService;
    @Autowired
    private BeEvalutionColumnService beEvalutionColumnService;
    @Autowired
    private BeSectionInfoService beSectionInfoService;

    private static final String LAYOUT_CODE_LEFT = "Left";

    private static final String PLEASE_SELECT = "pleaseSelect";

    /**
     * 保存
     *
     * @param @param  isFinish
     * @param @param  beEvalutionExpertDTO
     * @param @return
     * @param @throws Exception 参数
     * @return Response<String> 返回类型
     * @throws
     * @Title: saveEvalutionExpert
     */
    /**
     * @修改记录
     * @version 1.0
     * @author lhl
     * @date 2020-04-21 10:32
     * 1、检查是否存在表决
     */
    @PostMapping("/saveEvalutionExpert")
    @ApiOperation(value = "保存专家评审明细", response = BeEvalutionExpertDTO.class)
    public Response<String> saveEvalutionExpert(
            @ApiParam(name = "isFinish", value = "保存标志,1提交，0保存", required = true) @RequestParam("isFinish") String isFinish,
            @ApiParam(name = "isConfirm", value = "是否已经确认,1确认，0未确认") @RequestParam(name="isConfirm", required = false) String isConfirmStr,
            @RequestBody @ApiParam(name = "标段环节数据", value = "传入json格式", required = true) BeEvalutionExpertDTO beEvalutionExpertDTO) throws Exception {
        try {
            boolean isConfirm = Constants.STR_YES.equals(isConfirmStr);

            // 判断是否已终止项目
            beSectionInfoService.checkTermination(beEvalutionExpertDTO.getSectionId());
            // 检查是否存在表决
            beSectionInfoService.checkExistsVote(beEvalutionExpertDTO.getSectionId());

            //目前布局为Left的都是环节信息数据，不需要保存到评审表，过滤这部分脏数据
            if (LAYOUT_CODE_LEFT.equals(beEvalutionExpertDTO.getLayoutCode())) {
                return Response.fail("布局代码为Left的不需要保存数据！");
            }
            System.out.println("*****" + GsonUtil.toJson(beEvalutionExpertDTO) + "******");
            /**begin:2020-05-12 夏云飞 需求 QZRJ-13700 下拉选择框需支持打勾打叉之外的状态（请选择的状态）*/
            //专家提交时判断是否存在pleaseSelect（请选择）的数据
            if (Constants.ONE.toString().equals(isFinish) && GsonUtil.toJson(beEvalutionExpertDTO.getDataList()).indexOf(PLEASE_SELECT) > Constants.MINUSONE) {
                return Response.fail("还有评审项未评审，请检查");
            }
            /**end:2020-05-12 夏云飞 需求 QZRJ-13700 下拉选择框需支持打勾打叉之外的状态（请选择的状态）*/
            String userGuid = RequestUtil.getHeader("userGuid");
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            String sectionStepId = beEvalutionExpertDTO.getSectionStepId();
            if (tsUser != null) {
                List<ColumnHeader> columnList = beEvalutionExpertDTO.getColumnList();
                List<Map<String, Object>> dataList = beEvalutionExpertDTO.getDataList();
                if (columnList == null || dataList == null) {
                    return Response.fail("列字段或数据字段不能为空");
                }
                if (StringUtils.isEmpty(sectionStepId)) {
                    return Response.fail("环节id不可以为空");
                }
                BeSectionStep beSectionStep = beSectionStepService.getSectionStepBySeqId(sectionStepId);
                BeSectionExpertInfo beSectionExpertInfo = beSectionExpertInfoService.selectByLoginName(beEvalutionExpertDTO.getSectionId(), tsUser.getLoginName());
                //判断是否已经环节的数据操作记录
                BeSectionExpertProgress beSectionExpertProgress = beSectionExpertProgressService.selectByKey(sectionStepId, beSectionExpertInfo.getSeqId());
                if (beSectionExpertProgress == null) {
                    log.error("*****当前环节没有查询到操作记录*****");
                    return Response.fail("数据加载异常，请重新刷新");
                }
                String submitCode = beSectionExpertProgress.getSubmitCode();
                synchronized ((beSectionStep.getSeqId() + "saveEvalutionExpert").intern()) {
                    //判断当前专家在此环节是否已经提交
                    if(Constants.ONE.toString().equals(beSectionExpertProgress.getIsFinish())){
                        return Response.fail("当前用户在此环节已评审完成，请勿重复提交");
                    }
                    //新接口
                    beEvalutionOutcomeService.save(dataList, columnList, beSectionStep, beSectionExpertInfo.getSeqId(), beEvalutionExpertDTO.getLayoutCode(), submitCode, isFinish, isConfirm, beEvalutionColumnService.selectList());
                }

                return Response.ok("保存成功");

            } else {
                return Response.fail("获取专家账号登录信息失败");
            }
        } catch (BizException e) {
            log.error("LOG[]saveEvalutionExpert_116[]{},error={}","异常日志",GsonUtil.toJsonWithGson(e));
            return Response.fail(e.getMessage());
        } catch (Exception e) {
            log.error("LOG[]saveEvalutionExpert_131[]{},error={}","数据保存异常",GsonUtil.toJsonWithGson(e));
            return Response.fail("数据保存异常，请联系管理员！");
        }
    }
}
